import {defineStore} from 'pinia'
import {computed, ref} from "vue";
import Cookies from 'js-cookie'
import {getToken, setToken, removeToken} from "@/utils/auth";
import {userLogin} from "@/api/user";
import router, {resetRouter} from "@/router";

export const useGetTokenStore = defineStore('getToken', () => {
    const token = ref(undefined)
    function login(userInfo) {
        const {username, password} = userInfo
        return new Promise((resolve, reject) => {
            userLogin({account: username.trim(), password: password}).then(res => {
                token.value = res.token
                setToken(res.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    }

    function logout() {
        return new Promise((resolve) => {
            removeToken()
            resetRouter()
            resolve()
        })
    }

    function resetToken() {
        return new Promise((resolve, reject) => {
            removeToken()
            resolve()
        })
    }


    return {token, login, resetToken,logout}
})
